package com.kye.express.business.common_tool;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.Menu;
import android.view.MenuItem;

import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.express.R;
import com.kye.express.business.base.BaseToolbarActivity;
import com.kye.express.databinding.ActivityCommonToolBinding;
import com.kye.model.bean.common_tool.CommonToolItemBean;

import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import me.drakeet.multitype.MultiTypeAdapter;

public class CommonToolActivity extends BaseToolbarActivity implements CommonToolContract.CommonToolView {

    private final static String TAG_STATUS_TYPE = "TAG_STATUS_TYPE";
    private int statusType;
    private MenuItem menuItem = null;
    private ActivityCommonToolBinding binding;
    private CommonToolContract.CommonToolPresenter presenter;
    private MultiTypeAdapter selectedAdapter;
    private MultiTypeAdapter unselectedAdapter;
    private ItemTouchHelper selectedItemTouchHelper;
    private CommonToolItemDragHelperCallback dragHelperCallback;

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, CommonToolActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            savedInstanceState.getInt(TAG_STATUS_TYPE, CommonToolStatusType.STATUS_EMPTY);
        }
        binding = DataBindingUtil.setContentView(this, R.layout.activity_common_tool);
        setUpToolbar((Toolbar) findViewById(R.id.toolbar));
        setTitle(getString(R.string.common_tool));
        presenter = new CommonToolContract.CommonToolPresenter();
        presenter.bind(this);
        presenter.onCreate(savedInstanceState);
        initViews();
        initEvents();
        initData(savedInstanceState);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_commontools_add, menu);
        menuItem = menu.findItem(R.id.menuitem_commontools_add);
        return true;
    }

    private void initViews() {
        selectedAdapter = new MultiTypeAdapter();
//        selectedAdapter.setHasStableIds(true);
        selectedAdapter.register(CommonToolItemBean.class, new CommonToolItemViewBinder(presenter));
        binding.selectedCommonTools.setLayoutManager(new GridLayoutManager(this, 4));
        binding.selectedCommonTools.setAdapter(selectedAdapter);

        unselectedAdapter = new MultiTypeAdapter();
//        unselectedAdapter.setHasStableIds(true);
        unselectedAdapter.register(CommonToolItemBean.class, new CommonToolItemViewBinder(presenter));
        binding.unselectedCommonTools.setLayoutManager(new GridLayoutManager(this, 4));
        binding.unselectedCommonTools.setAdapter(unselectedAdapter);

    }

    @Override
    public void initSelectedDrag() {
        dragHelperCallback = new CommonToolItemDragHelperCallback(selectedAdapter, presenter.getSelectedCommonTools(), presenter);
        selectedItemTouchHelper = new ItemTouchHelper(dragHelperCallback);
        selectedItemTouchHelper.attachToRecyclerView(binding.selectedCommonTools);
    }

    @Override
    public void updateSelectedDrag(List<CommonToolItemBean> dataList) {
        dragHelperCallback.setDataList(dataList);
    }

    private void initEvents() {
        /**
         * 空内容界面进入编辑界面,添加新的常用工具
         */
        RxView.clicks(binding.addCommonTool)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycleDestroy())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        showEditPage();
                        initEditSelectedCommonTools(presenter.getSelectedCommonTools());
                        initEditUnselectedCommonTools(presenter.getUnselectedCommonTools());
                    }
                });

        binding.toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (!binding.getHideLoading()) {
                    return true;
                }
                switch (statusType) {
                    // 内容界面点击编辑进入编辑状态
                    case CommonToolStatusType.STATUS_CONTENT:
                        showEditPage();
                        initEditSelectedCommonTools(presenter.getSelectedCommonTools());
                        initEditUnselectedCommonTools(presenter.getUnselectedCommonTools());
                        dragHelperCallback.setCanDrag(false);
                        break;
                    // 编辑界面点击完成，完成编辑状态，保存数据
                    case CommonToolStatusType.STATUS_EDIT:
                        if (presenter.getSelectedCommonTools().size() <= 0) {
                            showEmptyPage();
                        } else {
                            showContentPage();
                            initContentSelectedCommonTools(presenter.getSelectedCommonTools());
                        }
                        dragHelperCallback.setCanDrag(true);
                        presenter.updateCommonToolItems();
                        break;
                    // 空内容界面，点击添加进入编辑状态
                    case CommonToolStatusType.STATUS_EMPTY:
                        showEditPage();
                        Logger.d("to add");
                        initEditSelectedCommonTools(presenter.getSelectedCommonTools());
                        initEditUnselectedCommonTools(presenter.getUnselectedCommonTools());
                        dragHelperCallback.setCanDrag(false);
                        break;
                    default:
                        break;
                }
                return true;
            }
        });
    }

    private void initData(Bundle savedInstanceState) {
        presenter.initCommonToolsData();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        presenter.onSaveInstanceState(outState);
        outState.putInt(TAG_STATUS_TYPE, statusType);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void showPageInit(List<CommonToolItemBean> commonToolItemBeans) {
        if (commonToolItemBeans.size() <= 0) {
            statusType = CommonToolStatusType.STATUS_EMPTY;
            showEmptyPage();
        } else {
            statusType = CommonToolStatusType.STATUS_CONTENT;
            showContentPage();
            initContentSelectedCommonTools(commonToolItemBeans);
        }
    }

    /**
     * 显示内容界面，初始化选中的数据状态
     *
     * @param commonToolItemBeans
     */
    @Override
    public void initContentSelectedCommonTools(List<CommonToolItemBean> commonToolItemBeans) {
        presenter.getInitContentSelectedDataSingle(commonToolItemBeans)
                .subscribe(new Consumer<List<CommonToolItemBean>>() {
                    @Override
                    public void accept(List<CommonToolItemBean> commonToolItemBeans) throws Exception {
                        selectedAdapter.setItems(commonToolItemBeans);
//                        selectedAdapter.notifyDataSetChanged();
                        selectedAdapter.notifyItemRangeChanged(0, commonToolItemBeans.size(), new Integer(0));
                    }
                });
    }

    /**
     * 显示编辑界面，初始化选中的数据的状态
     *
     * @param commonToolItemBeans
     */
    @Override
    public void initEditSelectedCommonTools(List<CommonToolItemBean> commonToolItemBeans) {
        presenter.getInitEditSelectedDataSingle(commonToolItemBeans)
                .subscribe(new Consumer<List<CommonToolItemBean>>() {
                    @Override
                    public void accept(List<CommonToolItemBean> commonToolItemBeans) throws Exception {
                        selectedAdapter.setItems(commonToolItemBeans);
//                        selectedAdapter.notifyDataSetChanged();
                        selectedAdapter.notifyItemRangeChanged(0, commonToolItemBeans.size(), new Integer(0));
                    }
                });
    }

    /**
     * 显示编辑界面，初始化未选中的数据的状态
     *
     * @param commonToolItemBeans
     */
    @Override
    public void initEditUnselectedCommonTools(List<CommonToolItemBean> commonToolItemBeans) {
        presenter.getInitEditUnselectedDataSingle(commonToolItemBeans)
                .subscribe(new Consumer<List<CommonToolItemBean>>() {
                    @Override
                    public void accept(List<CommonToolItemBean> commonToolItemBeans) throws Exception {
                        unselectedAdapter.setItems(commonToolItemBeans);
//                        unselectedAdapter.notifyDataSetChanged();
                        selectedAdapter.notifyItemRangeChanged(0, commonToolItemBeans.size(), new Integer(1));
                    }
                });
    }

    @Override
    public void showLoadingPage() {
        binding.setHideLoading(false);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

    /**
     * 显示空内容界面
     */
    @Override
    public void showEmptyPage() {
        if (menuItem != null) {
            menuItem.setTitle("添加");
        }
        statusType = CommonToolStatusType.STATUS_EMPTY;
        binding.setHideLoading(true);
        binding.setStatus(statusType);
    }

    /**
     * 显示已选的内容界面
     */
    @Override
    public void showContentPage() {
        if (menuItem != null) {
            menuItem.setTitle("编辑");
        }
        statusType = CommonToolStatusType.STATUS_CONTENT;
        binding.setHideLoading(true);
        binding.setStatus(statusType);
    }

    /**
     * 显示编辑界面
     */
    @Override
    public void showEditPage() {
        if (menuItem != null) {
            menuItem.setTitle("完成");
        }
        statusType = CommonToolStatusType.STATUS_EDIT;
        binding.setHideLoading(true);
        binding.setStatus(statusType);
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    public ActivityCommonToolBinding getBinding() {
        return binding;
    }

    @Override
    public int getStatusType() {
        return statusType;
    }

    @Override
    public MultiTypeAdapter getSelectedAdapter() {
        return selectedAdapter;
    }

    @Override
    public MultiTypeAdapter getUnselectedAdapter() {
        return unselectedAdapter;
    }
}
